package com.wayne.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wayne.blog.entity.Article;
import com.wayne.blog.entity.ArticleTag;
import com.wayne.blog.entity.Category;
import com.wayne.blog.entity.Tag;
import com.wayne.blog.mapper.ArticleMapper;
import com.wayne.blog.service.ArticleService;
import com.wayne.blog.service.CategoryService;
import com.wayne.blog.service.TagService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    private static final Logger logger = LoggerFactory.getLogger(ArticleServiceImpl.class);

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private TagService tagService;

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public Page<Article> getArticlePage(Page<Article> page, Long categoryId, String keyword) {
        logger.info("查询文章列表，分页参数：{}，分类ID：{}，关键词：{}", page, categoryId, keyword);
        
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Article::getDeleted, 0);  // 只查询未删除的文章
        
        if (categoryId != null) {
            wrapper.eq(Article::getCategoryId, categoryId);
        }
        if (StringUtils.hasText(keyword)) {
            wrapper.like(Article::getTitle, keyword);
        }
        wrapper.orderByDesc(Article::getCreateTime);
        
        Page<Article> articlePage = page(page, wrapper);
        logger.info("查询结果：{}", articlePage);
        
        if (articlePage.getRecords() != null && !articlePage.getRecords().isEmpty()) {
            fillArticleInfo(articlePage.getRecords());
        }
        
        return articlePage;
    }

    @Override
    public Article getArticleDetail(Long id) {
        Article article = getById(id);
        if (article != null) {
            fillArticleInfo(Arrays.asList(article));
        }
        return article;
    }

    @Override
    @Transactional
    public void saveArticle(Article article, List<Long> tagIds) {
        logger.info("保存文章，文章ID：{}，标签ID列表：{}", article.getId(), tagIds);
        save(article);
        if (tagIds != null && !tagIds.isEmpty()) {
            List<ArticleTag> articleTags = tagIds.stream()
                    .map(tagId -> {
                        ArticleTag articleTag = new ArticleTag();
                        articleTag.setArticleId(article.getId());
                        articleTag.setTagId(tagId);
                        return articleTag;
                    })
                    .collect(Collectors.toList());
            logger.info("准备保存文章标签关联：{}", articleTags);
            articleMapper.batchInsertArticleTags(articleTags);
        }
    }

    @Override
    @Transactional
    public void updateArticle(Article article, List<Long> tagIds) {
        logger.info("更新文章，文章ID：{}，标签ID列表：{}", article.getId(), tagIds);
        updateById(article);
        articleMapper.deleteArticleTags(article.getId());
        if (tagIds != null && !tagIds.isEmpty()) {
            List<ArticleTag> articleTags = tagIds.stream()
                    .map(tagId -> {
                        ArticleTag articleTag = new ArticleTag();
                        articleTag.setArticleId(article.getId());
                        articleTag.setTagId(tagId);
                        return articleTag;
                    })
                    .collect(Collectors.toList());
            logger.info("准备保存文章标签关联：{}", articleTags);
            articleMapper.batchInsertArticleTags(articleTags);
        }
    }

    @Override
    @Transactional
    public void deleteArticle(Long id) {
        articleMapper.deleteArticleTags(id);
        removeById(id);
    }

    @Override
    public List<Article> getRelatedArticles(Long id) {
        // 获取当前文章
        Article currentArticle = getById(id);
        if (currentArticle == null) {
            return new ArrayList<>();
        }

        // 获取同分类的文章
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Article::getCategoryId, currentArticle.getCategoryId())
                .ne(Article::getId, id)
                .orderByDesc(Article::getCreateTime)
                .last("LIMIT 5");
        List<Article> articles = list(wrapper);

        // 如果同分类文章不足5篇，获取最新文章补充
        if (articles.size() < 5) {
            LambdaQueryWrapper<Article> latestWrapper = new LambdaQueryWrapper<>();
            latestWrapper.ne(Article::getId, id);
            
            // 只有当已有文章列表不为空时，才添加notIn条件
            if (!articles.isEmpty()) {
                List<Long> existingIds = articles.stream()
                        .map(Article::getId)
                        .collect(Collectors.toList());
                latestWrapper.notIn(Article::getId, existingIds);
            }
            
            latestWrapper.orderByDesc(Article::getCreateTime)
                    .last("LIMIT " + (5 - articles.size()));
            articles.addAll(list(latestWrapper));
        }

        fillArticleInfo(articles);
        return articles;
    }

    @Override
    @Transactional
    public void likeArticle(Long articleId) {
        Article article = getById(articleId);
        if (article != null) {
            article.setLikeCount(article.getLikeCount() + 1);
            updateById(article);
        }
    }

    private void fillArticleInfo(List<Article> articles) {
        for (Article article : articles) {
            // 填充分类信息
            if (article.getCategoryId() != null) {
                Category category = categoryService.getById(article.getCategoryId());
                article.setCategory(category);
            }
            
            // 填充标签信息
            List<Tag> tags = articleMapper.getArticleTags(article.getId());
            article.setTags(tags);
        }
    }
}